iOS 获取控制器

在一个单例中控制页面跳转的时候,NSObject无法获取控制器,怎么解决呢?这里总结几种获取控制器的方法

在View中获取UIViewController

1
2
3
4
5
6
7
8
9
10
11
12
13
- (UIViewController*)viewController {
UIResponder *nextResponder = self;
do {
nextResponder = [nextResponder nextResponder];
if ([nextResponder isKindOfClass:[UIViewController class]])
return (UIViewController*)nextResponder;
} while (nextResponder != nil);
return nil;
}

UINavigationController获取顶部ViewController

1
self.navigationController.visibleViewController

获取当前展示顶层ViewController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
+ (UIViewController *)topViewController {
UIViewController *resultVC;
resultVC = [self _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
while (resultVC.presentedViewController) {
resultVC = [self _topViewController:resultVC.presentedViewController];
}
return resultVC;
}
+ (UIViewController *)_topViewController:(UIViewController *)vc {
if ([vc isKindOfClass:[UINavigationController class]]) {
return [self _topViewController:[(UINavigationController *)vc topViewController]];
} else if ([vc isKindOfClass:[UITabBarController class]]) {
return [self _topViewController:[(UITabBarController *)vc selectedViewController]];
} else {
return vc;
}
return nil;
}

获取当前ViewController的UINavigationController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
+ (UINavigationController *)nextNavigationController {
UIResponder *nextResponder = [self topViewController];
do {
nextResponder = [nextResponder nextResponder];
if ([nextResponder isKindOfClass:[UINavigationController class]])
return (UINavigationController*)nextResponder;
} while (nextResponder != nil);
UITabBarController *rootVC = (UITabBarController *)[[UIApplication sharedApplication].delegate window].rootViewController;
return rootVC.selectedViewController;
}